package com.landeb.shop.huo.act;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.adapter.ActInvoiceEditLVAdapter;
import com.landeb.shop.huo.bean.BeanActInvoiceEdit;
import com.landeb.shop.huo.bean.ItemActInvoiceEdit;
import com.landeb.shop.huo.httpRequest.ActAddressSelectRequest;
import com.landeb.shop.huo.httpRequest.ActInvoiceEditRequest;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class InvoiceEditActivity extends BaseActivity implements View.OnClickListener {

    private SwipeRefreshLayout mSRL;

    private LinearLayout btnBack;
    private EditText etName;
    private Button btnCommit, btnCancel;
    private RadioGroup rgInvoiceTitle;
    private RadioButton rbPersonal, rbCompany;
    private ListView mListView;
    private ActInvoiceEditLVAdapter mAdapter;
    private List<ItemActInvoiceEdit> mList;


    private OkHttpClient client;
    private String mUrl;
    private Retrofit mRetrofit;
    private ActInvoiceEditRequest mRequest;
    private boolean isRefreshing = false;

    private String mPersonal, mCompany;

    private String mInvoiceName = null;
    private String mInvoiceType = null;
    private String mInvoiceMsg = null;

    public static void toAct(Context context) {
        Intent intent = new Intent(context, InvoiceEditActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invoice_edit);

        client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(ActInvoiceEditRequest.class);

        initView();
        initData();
        initEvent();

        refresh();

    }

    private void refresh() {

        if (!isRefreshing) {

            mSRL.setRefreshing(true);
            isRefreshing = true;

            mRequest.getInvoice()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanActInvoiceEdit>() {
                        @Override
                        public void onCompleted() {
                            mSRL.setRefreshing(false);
                            isRefreshing = false;
                            Log.e("getInvoice", "onCompleted: ");
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e("getInvoice", "onError: " + e.toString());
                            mSRL.setRefreshing(false);
                            isRefreshing = false;

                        }

                        @Override
                        public void onNext(BeanActInvoiceEdit beanActInvoiceEdit) {

                            if (beanActInvoiceEdit.getStatus() == 1) {

                                mPersonal = beanActInvoiceEdit.getData().getPerson();
                                mCompany = beanActInvoiceEdit.getData().getCompany();

                                if (rgInvoiceTitle.getCheckedRadioButtonId() == R.id.act_invoice_edit_RB_personal) {
                                    etName.setText(mPersonal);

                                } else if (rgInvoiceTitle.getCheckedRadioButtonId() == R.id.act_invoice_edit_RB_company) {
                                    etName.setText(mCompany);
                                }

                                List<String> mMsg = beanActInvoiceEdit.getData().getList();

                                mList.clear();
//                                for (String s : mMsg) {
//                                    ItemActInvoiceEdit item_score_log_act_rv = new ItemActInvoiceEdit(s, false);
//                                    mList.add(item_score_log_act_rv);
//                                }

                                for (int i = 0; i <mMsg.size() ; i++) {
                                    if (i==0){

                                        ItemActInvoiceEdit item = new ItemActInvoiceEdit(mMsg.get(i), true);
                                        mList.add(item);
                                        continue;
                                    }

                                    ItemActInvoiceEdit item = new ItemActInvoiceEdit(mMsg.get(i), false);
                                    mList.add(item);
                                }

                                mAdapter.notifyDataSetChanged();

                            } else {
                                Toast.makeText(InvoiceEditActivity.this, beanActInvoiceEdit.getInfo(), Toast.LENGTH_SHORT).show();
                            }


                        }
                    });
        }

    }

    private void initEvent() {

        btnBack.setOnClickListener(this);
        btnCommit.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

        mSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        rgInvoiceTitle.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.act_invoice_edit_RB_personal:
                        // TODO: 2016/11/29 选中个人
                        if (mPersonal != null) {
                            etName.setText(mPersonal);
                        }
                        break;

                    case R.id.act_invoice_edit_RB_company:
                        // TODO: 2016/11/29 选中单位
                        if (mCompany != null) {
                            etName.setText(mCompany);
                            break;
                        }
                }
            }

        });


        rbPersonal.setChecked(true);
//        rbPersonal.performClick();

        mAdapter = new ActInvoiceEditLVAdapter(InvoiceEditActivity.this, mList);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                for (ItemActInvoiceEdit item : mList) {

                    item.setChecked(false);

                }

                mList.get(position).setChecked(true);

                mAdapter.notifyDataSetChanged();

            }
        });


    }


    private void initData() {
        mList = new ArrayList<>();
    }

    private void initView() {

        mSRL = (SwipeRefreshLayout) findViewById(R.id.act_invoice_edit_srl);
        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));

        btnBack = (LinearLayout) findViewById(R.id.act_invoice_edit_btn_back);

        rgInvoiceTitle = (RadioGroup) findViewById(R.id.act_invoice_edit_RG_invoiceTitle);
        rbPersonal = (RadioButton) findViewById(R.id.act_invoice_edit_RB_personal);
        rbCompany = (RadioButton) findViewById(R.id.act_invoice_edit_RB_company);
        etName = (EditText) findViewById(R.id.act_invoice_edit_et_name);

        mListView = (ListView) findViewById(R.id.act_invoice_edit_lv);

        btnCommit = (Button) findViewById(R.id.act_invoice_edit_btn_commit);
        btnCancel = (Button) findViewById(R.id.act_invoice_edit_btn_cancel);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.act_invoice_edit_btn_back:
                // TODO: 2016/11/29 返回键
                onBackPressed();
                break;

            case R.id.act_invoice_edit_btn_commit:
                // TODO: 2016/11/29 提交按钮

              if(rgInvoiceTitle.getCheckedRadioButtonId()==R.id.act_invoice_edit_RB_personal) {
                  mInvoiceType="个人";
              }else if(rgInvoiceTitle.getCheckedRadioButtonId()==R.id.act_invoice_edit_RB_company){
                  mInvoiceType="单位";
              }


                mInvoiceName = etName.getText().toString();

                for (ItemActInvoiceEdit i : mList) {
                    if (i.isChecked()) {
                        mInvoiceMsg = i.getItem();
                    }
                }


                if (TextUtils.isEmpty(mInvoiceType)) {
                    Toast.makeText(this, "请选择发票类型", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(mInvoiceName)) {
                    Toast.makeText(this, "请输入发票抬头", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(mInvoiceMsg)) {
                    Toast.makeText(this, "请选择发票内容", Toast.LENGTH_SHORT).show();
                    return;
                }


                Intent intent = new Intent();

                intent.putExtra("type", mInvoiceType);
                intent.putExtra("name", mInvoiceName);
                intent.putExtra("msg", mInvoiceMsg);

                setResult(RESULT_OK, intent);
                finish();

                break;

            case R.id.act_invoice_edit_btn_cancel:
                // TODO: 2016/11/30 取消按钮
                setResult(RESULT_CANCELED);
                finish();
                break;

        }
    }
}
